<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/7/13
 * Time: 下午4:27
 */

namespace app\index\controller;

use Alipay\Alipayobj;
use app\common\controller\CreateNotify;
use app\common\controller\Deviceobj;
use app\common\controller\TemplateMsg;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use think\Session;
use Wechat\Wxobjopen;


class Lftpay extends PayBase
{
    public $version = "1.0";
//    public $partner_id="18060410173207886";
    public $input_charset = "UTF-8";
//    public $core_merchant_no="EW_N5772984681";
    public $sign_type = "MD5";
//    public $partner_key="78bc1ac50be17004b58edea930c70c78";
    public $submit_url = "http://newfront.liantuobank.com/NewFront/base/gateway.in";

    public function tests()
    {
        $request = request();

        $openid = $request->param('openId');
        var_dump($openid);
    }

    public function pay()
    {

        $request = request();

//        Session::set('openid', null);
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
//        $Agent = new Agent();
//        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $openid = $request->param('openId');
        if (empty($openid)) {
            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("lftpay/pay", array('id' => $request->param('id')));
            $url = "http://api.liantuofu.com/open/wechatUserAuth?merchantCode={$user['lft_merchant_no']}&redirectUri={$callback}";


            header("Location: $url");
        }

        $jssdk = "";
        $this->assign('jssdk', $jssdk);

        $this->assign("channel", "wxpay");
        $this->assign("headimg", $user['img']);
        $this->assign('mach', $user);
        $this->assign('id', $request->param('id'));
        $this->assign('openid', $openid);
        return $this->fetch();

    }

    public function alipay()
    {
        try {
            $request = request();
            $Merchant = new Merchant();
            $users = $Merchant->where(array('id' => $request->param('id')))->find();
            $Agent = new Agent();
            $agent = $Agent->where(array('id' => $users['agent']))->find();
            $raskey = $agent['ali_app_key'];
            $options = array(
                //'token' => $config ["token"], // 填写你设定的key
                //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
                'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
                'rsaPrivateKey' => $agent['ali_app_key'],
            );
            $aliObj = new Alipayobj($options);
            if ($request->get('auth_code')) {
                $param['app_id'] = $agent['ali_app_id'];
                $param['method'] = "alipay.system.oauth.token";
                $param['charset'] = "UTF-8";
                $param['sign_type'] = "RSA2";
                $param['version'] = '1.0';
                $param['timestamp'] = date('Y-m-d H:i:s');
                $param['grant_type'] = 'authorization_code';
                $param['code'] = $request->get('auth_code');
                $signContent = $aliObj->rsaSign($param, $signType = "RSA2");

                $param['sign'] = $signContent;
                $uid = $aliObj->getuid($param);
                $user = json_decode($uid, true);
                $uid = $user['alipay_system_oauth_token_response']['user_id'];
//            echo $uid;
                $this->assign("headimg", $users['img']);
                $this->assign('shmc', $users['merchant']);
                $this->assign('id', $request->param('id'));
                $this->assign('uid', $uid);
                $this->assign('mach', $users);
                $this->assign("channel", "alipay");

                return $this->fetch('alipay');

            } else {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Lftpay/alipay", array('id' => $request->param('id')));
                $url = $aliObj->getOauthRedirect($callback, '', 'auth_base');
//        echo $url;
//        exit();
                header("Location: $url");
            }
        } catch (\Exception $e) {
            echo "配置错误:" . $e->getMessage();
        }

    }

    public function alipaypay()
    {
        $User = new Merchant();
        $machinfos = $User->where(array('id' => request()->param('id')))->find();
        $head["service"] = "front.jsapi";//扫码--公众号支付
        $head["version"] = $this->version;//默认版本号
        $head["partner_id"] = $machinfos['lft_pid'];//联富通线下提供pid
        $head["input_charset"] = $this->input_charset; //编码格式，默认只支持UTF-8
        $head["core_merchant_no"] = $machinfos['lft_core_merchant_no'];//联富通后台核心商户编号
        $head["sign_type"] = $this->sign_type;//加密方式，默认只支持MD5;
        $body["merchant_no"] = $machinfos['lft_merchant_no']; //门店商户编号
        $body["channel_type"] = "ALI";//支付渠道
        $body["out_trade_no"] = request()->post('orderid');;//商户订单号
        $body["total_amount"] = number_format(request()->post('price'), 2,".","");; //订单总金额
        $body["subject"] = "快捷支付";//商品标题
        $body["spbill_create_ip"] = request()->ip();//终端IP
        $body["device_info"] = "在线支付";//设备号
        $body["open_id"] = request()->post('buyer_id');//            //对应的appid获取的用户openid
        $body["notify_url"] = "https://os.wunengkeji.com/index.php?s=/lftpay/lftnotify";//暂未开通，商户自己服务器被动接收支付结果的服务器地址
        $data['orderid'] = request()->post('orderid');
        $data['mid'] = request()->param('id');
//            $data['openid'] = request()->post('openid');
        $data['openid'] = request()->post('buyer_id');
        $data['pay_statu'] = 0;
        $data['pay_fs'] = 1;
        $data['price'] = request()->post('price');
        $data['yf_price'] = request()->post('price');
        $data['add_time'] = time();
        $data['attach'] = request()->post('attach');

        $Paylog = new Paylog();
        $add = $Paylog->save($data);
        $signArray = array_merge($head, $body);

        $sign = $this->createSign($signArray, $machinfos['lft_key']);
        $head["sign"] = $sign;

        $requestJson["body"] = $body;
        $requestJson["head"] = $head;
        $requestPara["requestJson"] = json_encode($requestJson);
        $resp = $this->requestAsHttpPOST($requestPara, $this->submit_url); //发送请求
        file_put_contents('/data2/html/payos/lftpay1111.log',$resp);
        file_put_contents('/data2/html/payos/lftpay1112.log',$requestPara["requestJson"]);

        $resp = json_decode($resp, true);
        $re_msg = $resp['body'];
//        file_put_contents('/data2/html/payos/lftpay1111.log',json_encode($resp,256));

//        return json($re_msg);

        if ($re_msg['is_success'] == "S") {
            if ($re_msg['prepay_id'] == '') {

                $param = json_encode(array('code' => 2, 'message' => '接口错误'));

            } else {
                $param = $re_msg['prepay_id'];
            }
        } else {
            $param = json_encode(array('code' => 2, 'message' => '接口错误'));

        }
        return json($param);

    }

    public function pay2()
    {
        $User = new Merchant();
        $machinfos = $User->where(array('id' => request()->param('id')))->find();
        $sub_appid = "wx6ea29f2839fa6aa0";
        $head["service"] = "front.jsapi";//扫码--公众号支付
        $head["version"] = $this->version;//默认版本号
        $head["partner_id"] = $machinfos['lft_pid'];//联富通线下提供pid
        $head["input_charset"] = $this->input_charset; //编码格式，默认只支持UTF-8
        $head["core_merchant_no"] = $machinfos['lft_core_merchant_no'];//联富通后台核心商户编号
        $head["sign_type"] = $this->sign_type;//加密方式，默认只支持MD5;
        $body["merchant_no"] = $machinfos['lft_merchant_no']; //门店商户编号
        $body["channel_type"] = "WX";//支付渠道
        $body["out_trade_no"] = request()->post('orderid');;//商户订单号
        $body["total_amount"] =number_format(request()->post('price'), 2,".","");; //订单总金额
        $body["subject"] = "快捷支付";//商品标题
        $body["spbill_create_ip"] = request()->ip();//终端IP
        $body["device_info"] = "在线支付";//设备号
        $body["open_id"] = request()->post('sub_openid');//            //对应的appid获取的用户openid
        $body["sub_appid"] = $sub_appid;//联富通后台门店进件时填写的appid,传递参数时针对于所有的商户全部都为sub_appid
        $body["notify_url"] = "https://os.wunengkeji.com/index.php?s=/lftpay/lftnotify";//暂未开通，商户自己服务器被动接收支付结果的服务器地址
        $data['orderid'] = request()->post('orderid');
        $data['mid'] = request()->param('id');
//            $data['openid'] = request()->post('openid');
        $data['openid'] = request()->post('sub_openid');
        $data['pay_statu'] = 0;
        $data['price'] = request()->post('price');
        $data['yf_price'] = request()->post('price');
        $data['pay_fs'] = 0;
        $data['add_time'] = time();
        $data['attach'] = request()->post('attach');

        $Paylog = new Paylog();
        $add = $Paylog->save($data);
        $signArray = array_merge($head, $body);

        $sign = $this->createSign($signArray, $machinfos['lft_key']);
        $head["sign"] = $sign;

        $requestJson["body"] = $body;
        $requestJson["head"] = $head;
//        file_put_contents('/data2/html/payos/123456.txt',"up".json_encode($requestJson),8);
        $requestPara["requestJson"] = json_encode($requestJson);

        $resp = $this->requestAsHttpPOST($requestPara, $this->submit_url); //发送请求
        $resp = json_decode($resp, true);
        $re_msg = $resp['body'];
//        return json_encode($resp,JSON_UNESCAPED_UNICODE);

//        file_put_contents('/data2/html/payos/123456aaa.txt',"down".json_encode($resp),8);


        if ($re_msg['is_success'] == "S") {
            if ($re_msg['pay_info'] == '') {

                $param = json_encode(array('code' => 2, 'message' => '接口错误'));

            } else {

                $param = json_decode($re_msg['pay_info'], true);
            }
        } else {
            $param = json_encode(array('code' => 2, 'message' => '接口错误'));

        }

        return json($param);

    }

    public function test()
    {
        $Paylog = new Paylog();
        $payinfoa = $Paylog->where(['orderid' => "H687-2018082316083871853"])->find();
        $s = action('Index/sendprint', array($payinfoa));
        var_dump($s);
    }

    public function orderquery($orderid)
    {
        try {
            $Paylog = new Paylog();
            $payinfoa = $Paylog->where(['orderid' => $orderid])->find();
            $User = new Merchant();
            $machinfos = $User->where(array('id' => $payinfoa['mid']))->find();
            $head["service"] = "front.query";//订单查询API
            $head["version"] = $this->version;//默认版本号
            $head["partner_id"] = $machinfos['lft_pid'];;//联富通线下提供pid
            $head["input_charset"] = $this->input_charset; //编码格式，默认只支持UTF-8
            $head["core_merchant_no"] = $machinfos['lft_core_merchant_no'];;//联富通后台核心商户编号
            $head["sign_type"] = $this->sign_type;//加密方式，默认只支持MD5

            $body["out_trade_no"] = $orderid;//商户订单号
//        $body["trade_no"]            ="00060011806081011119020239178664";//交易流水号,支付请求返回结果参数
            $signArray = array_merge($head, $body);
            $sign = $this->createSign($signArray, $machinfos['lft_key']);
            $head["sign"] = $sign;
            $requestJson["body"] = $body;
            $requestJson["head"] = $head;
            $requestPara["requestJson"] = json_encode($requestJson);
            $resp = $this->requestAsHttpPOST($requestPara, $this->submit_url); //发送请求
            $re_msg = json_decode($resp, true);
            $param = $re_msg['body'];
//        file_put_contents('/data2/html/actionlog/lft/notify2.log', json_encode($param), 8);
            if ($param['is_success'] == "S") {

                if ($param['trade_status'] == "success") {

                    $pays['orderno'] = $param['pay_channel_trade_no'];
                    $pays['pay_time'] = $param['gmt_payment'];
                    $pays['pay_statu'] = 1;
                    $pays['openid'] = isset($param['openid']) ? $param['openid'] : "";;
                    $pays['sub_openid'] = isset($param['sub_openid']) ? $param['sub_openid'] : "";
                    $pays['payinfo'] = json_encode($param);
                    $pays['price'] = $param['total_amount'];
                    $pays['trade_no'] = $param['pay_channel_out_trade_no'];
                    $Paylog->where(array('orderid' => $payinfoa['orderid']))->update($pays);
                    if ((int)$payinfoa['tzzt'] == 0) {
                        $da['tzzt'] = 1;
                        $Paylog->where(['orderid' => $payinfoa['orderid']])->update($da);
                        $Deviceobj = new Deviceobj();
                        $s['dev'] =$Deviceobj->ylb_sendvoice($payinfoa['orderid']);
                        $s['wx'] = action('Wxauth/sendtemplate', array($payinfoa['mid'], $payinfoa['orderid']));
                        action('Index/sendprint', array($payinfoa));
                        $da1['tzmsg'] = json_encode($s);
                        $Paylog->where(['orderid' => $payinfoa['orderid']])->update($da1);
                        $notify_param['merchantid']=$payinfoa['mid'];
                        $notify_param['out_trade_no']=$payinfoa['orderid'];
                        $CreateNotify=new CreateNotify();
                        $CreateNotify->pay_notify($notify_param);
                    }
                    $datas['result_code'] = "SUCCESS";
                    $datas['result_msg'] = "SUCCESS";
                } else {
                    $datas['result_code'] = "FAIL";
                    $datas['result_msg'] = $param['error'] . $param['message'];
                }
            } else {
                $datas['result_code'] = "FAIL";
                $datas['result_msg'] = $param['error'] . $param['message'];

            }
        } catch (\Exception $e) {
            $datas['result_code'] = "FAIL";
            $datas['result_msg'] = $e->getMessage() . $e->getFile() . ":" . $e->getLine();
        }
        file_put_contents('/data2/html/payos/exelog/lftorderquery.txt', time().'-r:'.json_encode($datas), 8);
        return $datas;

    }

    public function payover()
    {

        $orderid = request()->param('orderid');
        $sj = $this->orderquery($orderid);

        if ($sj['result_code'] == "SUCCESS") {

            $data = 0;
        } else {
            $data = 1;
        }
        echo $data;
    }

    public function orderinfo()
    {
        $request = request();
        //广告
        $Adview = new Adview();
        $ad_type = $Adview->getadtype($request->param('orderid'));
//        file_put_contents('/data2/html/payos/payad.txt', json_encode($ad_type), 8);
        if ($ad_type['ad_type'] == '1') {
            $Adview->getadvert($request->param('orderid'));
        }


        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();


        $map['id'] = $request->param('id');
        $config = $Merchant->where($map)->find();
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => 19))->find();
//        $config2 = $System->where(array('id' => 1))->find();
        $options = array(
            'component_token' => $agent['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $agent['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $agent['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $agent['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $agent['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );

        $weObj = new Wxobjopen($options);
        $openid = session('openid');

        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("lftpay/orderinfo", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {

                $openid = $info['openid'];

            }
        }

        $maq['orderid'] = $request->param('orderid');

        $Paylog = new Paylog();
        $order = $Paylog->where($maq)->find();
        $order['deduzkinfo'] = $this->getdeduzkinfo($order['hx_card'], $order['gel_card_zk']);
//        var_dump($order['openid']);
        if ($openid == $order['openid'] || $openid == $order['sub_openid']) {

            $mav['id'] = $request->param('id');
            $Merchant = new Merchant();
            $shmc = $Merchant->where($mav)->value('merchant');


            $this->assign('shmc', $shmc);
            $this->assign('order', $order);
            $this->assign('id', $request->param('id'));
            $this->assign('orderid', $request->param('orderid'));
        } else {
            $this->error('非订单支付者无法查看订单详情');
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        $this->assign('jssdk', $jssdk);
        return $this->fetch('index/orderinfo');
    }

    public function orderinfoali()
    {
//halt(123);
        $Adview = new Adview();
        $request = request();
        $ad_type = $Adview->getadtype($request->param('orderid'));
//        file_put_contents('/data2/html/payos/payad.txt', json_encode($ad_type), 8);
        if ($ad_type['ad_type'] == '1') {
            $Adview->getadvert($request->param('orderid'));
        }


        $Merchant = new Merchant();
        $Agent = new Agent();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
//        halt($options);
        $aliObj = new Alipayobj($options);

        if ($request->param('auth_code') || request()->get('auth_code')) {
            $param['app_id'] = $agent['ali_app_id'];
            $param['method'] = "alipay.system.oauth.token";
            $param['charset'] = "UTF-8";
            $param['sign_type'] = "RSA2";
            $param['version'] = '1.0';
            $param['timestamp'] = date('Y-m-d H:i:s');
            $param['grant_type'] = 'authorization_code';
            $param['code'] = $request->param('auth_code') ? $request->param('auth_code') : $request->get('auth_code');
            $signContent = $aliObj->rsaSign($param, $signType = "RSA2");

            //$sign2 = $aliObj->alonersaSign($signContent, $raskey, $signType = "RSA", $keyfromfile = false);

            // var_dump($sign);
            $param['sign'] = $signContent;
            $uid = $aliObj->getuid($param);
            $user = json_decode($uid, true);
            $this->uid = $user['alipay_system_oauth_token_response']['user_id'];


        } else {

            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Alipay/orderinfo", array('id' => $request->param('id'), 'orderid' => $request->param('orderid')));
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_userinfo');
            header("Location: $url");
        }


        $maq['orderid'] = $request->param('orderid');
        $Paylog = new Paylog();
        $order = $Paylog->where($maq)->find();
        $mav['id'] = $request->param('id');
        $Merchant = new Merchant();
        $shmc = $Merchant->where($mav)->value('merchant');


        $this->assign('shmc', $shmc);
        $this->assign('order', $order);
        $this->assign('id', $request->param('id'));
        $this->assign('orderid', $request->param('orderid'));
//        } else {
//            $this->error('非订单支付者无法查看订单详情');
//        }
        return $this->fetch("alipay/orderinfo");
    }

    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "-" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }
    //联富通调用
    //发起请求类
    public function createSign($paras, $key)
    {
        $sort_array = $this->array_sort(array_filter($paras));                //删除数组中的空值并排序
        $prestr = $this->create_linkstring($sort_array);                    //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        $prestr = $prestr . $key;                                        //把拼接后的字符串再与安全校验码直接连接起来
        $mysgin = $this->sign($prestr, $paras["sign_type"]);                //把最终的字符串签名，获得签名结果
        return $mysgin;
    }

    public function array_sort($array)
    {
        ksort($array);                                                //按照key值升序排列数组
        return $array;
    }

    /**
     * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
     * $array 需要拼接的数组
     * return 拼接完成以后的字符串
     */
    public function create_linkstring($array)
    {
        $str = "";
        while (list ($key, $val) = each($array)) {
            //键值为空的参数不参与排序，键名为key的参数不参与排序
            if ($val != null && $val != "" && $key != "key" && $key != "sign_type")
                $str .= $key . "=" . $val . "&";
        }
        $str = substr($str, 0, count($str) - 2);                        //去掉最后一个&字符
        return $str;                                                //返回参数
    }

    /**
     * 签名字符串
     * $prestr 需要签名的字符串
     * $sign_type 签名类型，也就是sec_id
     * return 签名结果
     */
    public function sign($prestr, $sign_type)
    {
        $sign = '';
        if ($sign_type == 'MD5') {
            $sign = md5($prestr);                                    //MD5加密
        } elseif ($sign_type == 'DSA') {
            //DSA 签名方法待后续开发
            die("DSA 签名方法待后续开发，请先使用MD5签名方式");
        } elseif ($sign_type == "") {
            die("sign_type为空，请设置sign_type");
        } else {
            die("暂不支持" . $sign_type . "类型的签名方式");
        }
        return strtolower($sign);                                    //返回参数并小写
    }


    public function requestAsHttpPOST($data, $service_url)
    {
        $HTTP_TIME_OUT = "20";
        $http_data = $this->array_sort(array_filter($data)); //删除数组中的空值并排序
        $post_data = http_build_query($http_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded;charset=MD5',
                'content' => $post_data,
                'timeout' => $HTTP_TIME_OUT * 1000 //超时时间,*1000将毫秒变为秒（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($service_url, false, $context);
        return $result;
    }

//异步接受
    public function lftnotify()
    {
        $postStr = file_get_contents('php://input');
        $param = urldecode($postStr);
        $param = explode("=", $param);

        $param = json_decode($param[1], true);

        if ($param['body']['is_success'] == "S") {
            $ss = $this->orderquery($param['body']['out_trade_no']);
//            file_put_contents('/data2/html/actionlog/lft/notify.log', json_encode($ss), 8);
            return "success";
        }

    }
}